<template>
  <div class="config-view">
    <div class="config-container">
      <h2>API配置</h2>
      <p class="description">在此页面配置API连接参数。更改后将自动保存并应用于新会话。</p>
      
      <!-- 标签页切换 -->
      <div class="tabs">
        <div 
          class="tab" 
          :class="{ 'active': activeTab === 'ragflow' }"
          @click="activeTab = 'ragflow'"
        >
          RAGFlow API
        </div>
        <div 
          class="tab" 
          :class="{ 'active': activeTab === 'openai' }"
          @click="activeTab = 'openai'"
        >
          OpenAI兼容API
        </div>
      </div>
      
      <div v-if="activeTab === 'ragflow'">
        <form @submit.prevent="saveConfig" class="config-form">
          <div class="form-group">
            <label for="api-key">API Key</label>
            <input 
              type="text" 
              id="api-key" 
              v-model="config.apiKey"
              placeholder="输入API Key (例如: ragflow-xxx...)" 
              class="form-control"
            />
          </div>
          
          <div class="form-group">
            <label for="base-url">Base URL</label>
            <input 
              type="text" 
              id="base-url" 
              v-model="config.baseUrl" 
              placeholder="输入RAGFlow服务地址 (例如: http://127.0.0.1)" 
              class="form-control"
            />
          </div>
          
          <div class="form-group">
            <label for="chat-id">Chat ID</label>
            <input 
              type="text" 
              id="chat-id" 
              v-model="config.chatId" 
              placeholder="输入聊天ID (例如: f596b90c...)" 
              class="form-control"
            />
          </div>
          
          <div class="form-actions">
            <button type="submit" class="primary">保存配置</button>
            <button type="button" class="secondary" @click="resetDefaults('ragflow')">恢复默认</button>
          </div>
        </form>
      </div>
      
      <div v-if="activeTab === 'openai'">
        <form @submit.prevent="saveConfig" class="config-form">
          <div class="form-group">
            <label for="openai-api-key">API Key</label>
            <input 
              type="text" 
              id="openai-api-key" 
              v-model="config.openaiApiKey"
              placeholder="输入OpenAI API Key (例如: sk-xxx...)" 
              class="form-control"
            />
          </div>
          
          <div class="form-group">
            <label for="openai-base-url">Base URL</label>
            <input 
              type="text" 
              id="openai-base-url" 
              v-model="config.openaiBaseUrl" 
              placeholder="输入API地址 (例如: https://api.openai.com/v1)" 
              class="form-control"
            />
          </div>
          
          <div class="form-group">
            <label for="openai-model">模型</label>
            <input 
              type="text" 
              id="openai-model" 
              v-model="config.openaiModel" 
              placeholder="输入模型名称 (例如: gpt-3.5-turbo)" 
              class="form-control"
            />
          </div>
          
          <div class="form-actions">
            <button type="submit" class="primary">保存配置</button>
            <button type="button" class="secondary" @click="resetDefaults('openai')">恢复默认</button>
          </div>
        </form>
      </div>
      
      <div v-if="message" :class="['message', messageType]">
        {{ message }}
      </div>
      
      <div class="current-config">
        <h3>当前配置</h3>
        <pre>{{ currentConfigDisplay }}</pre>
      </div>
    </div>
  </div>
</template>

<script>
// 导入默认配置
import { 
  API_KEY, BASE_URL, CHAT_ID,
  OPENAI_API_KEY, OPENAI_BASE_URL, OPENAI_MODEL,
  getConfig, saveConfig
} from '../services/apiConfig';

export default {
  name: 'ConfigView',
  data() {
    return {
      activeTab: 'ragflow',
      config: {
        apiKey: '',
        baseUrl: '',
        chatId: '',
        openaiApiKey: '',
        openaiBaseUrl: '',
        openaiModel: ''
      },
      message: '',
      messageType: 'success', // success或error
      defaultConfig: {
        apiKey: API_KEY,
        baseUrl: BASE_URL,
        chatId: CHAT_ID,
        openaiApiKey: OPENAI_API_KEY,
        openaiBaseUrl: OPENAI_BASE_URL,
        openaiModel: OPENAI_MODEL
      },
      messageTimer: null // 存储定时器ID
    };
  },
  computed: {
    currentConfigDisplay() {
      return JSON.stringify({
        RAGFlow: {
          API_KEY: this.config.apiKey || this.defaultConfig.apiKey,
          BASE_URL: this.config.baseUrl || this.defaultConfig.baseUrl,
          CHAT_ID: this.config.chatId || this.defaultConfig.chatId
        },
        OpenAI: {
          API_KEY: this.maskApiKey(this.config.openaiApiKey || this.defaultConfig.openaiApiKey),
          BASE_URL: this.config.openaiBaseUrl || this.defaultConfig.openaiBaseUrl,
          MODEL: this.config.openaiModel || this.defaultConfig.openaiModel
        }
      }, null, 2);
    }
  },
  created() {
    // 从localStorage加载配置，在created而不是mounted中执行
    this.loadConfig();
  },
  methods: {
    maskApiKey(key) {
      if (!key) return '';
      if (key.length < 8) return '****';
      return key.substring(0, 4) + '****' + key.substring(key.length - 4);
    },
    loadConfig() {
      // 从localStorage加载配置
      const savedConfig = localStorage.getItem('ragflow_config');
      
      if (savedConfig) {
        try {
          const parsedConfig = JSON.parse(savedConfig);
          // 设置数据
          this.config.apiKey = parsedConfig.apiKey || this.defaultConfig.apiKey;
          this.config.baseUrl = parsedConfig.baseUrl || this.defaultConfig.baseUrl;
          this.config.chatId = parsedConfig.chatId || this.defaultConfig.chatId;
          this.config.openaiApiKey = parsedConfig.openaiApiKey || this.defaultConfig.openaiApiKey;
          this.config.openaiBaseUrl = parsedConfig.openaiBaseUrl || this.defaultConfig.openaiBaseUrl;
          this.config.openaiModel = parsedConfig.openaiModel || this.defaultConfig.openaiModel;
        } catch (e) {
          console.error('加载配置失败:', e);
          this.resetDefaults();
        }
      } else {
        // 如果没有保存的配置，使用默认值
        this.resetDefaults();
      }
    },
    saveConfig() {
      try {
        // 清除之前的定时器
        if (this.messageTimer) {
          clearTimeout(this.messageTimer);
          this.messageTimer = null;
        }
        
        // 构建完整配置对象
        const configData = {
          apiKey: this.activeTab === 'ragflow' ? this.config.apiKey : undefined,
          baseUrl: this.activeTab === 'ragflow' ? this.config.baseUrl : undefined,
          chatId: this.activeTab === 'ragflow' ? this.config.chatId : undefined,
          openaiApiKey: this.activeTab === 'openai' ? this.config.openaiApiKey : undefined,
          openaiBaseUrl: this.activeTab === 'openai' ? this.config.openaiBaseUrl : undefined,
          openaiModel: this.activeTab === 'openai' ? this.config.openaiModel : undefined,
        };
        
        // 使用当前配置补全缺失字段
        const currentConfig = getConfig();
        const combinedConfig = {
          apiKey: configData.apiKey !== undefined ? configData.apiKey : currentConfig.apiKey,
          baseUrl: configData.baseUrl !== undefined ? configData.baseUrl : currentConfig.baseUrl,
          chatId: configData.chatId !== undefined ? configData.chatId : currentConfig.chatId,
          openaiApiKey: configData.openaiApiKey !== undefined ? configData.openaiApiKey : currentConfig.openaiApiKey,
          openaiBaseUrl: configData.openaiBaseUrl !== undefined ? configData.openaiBaseUrl : currentConfig.openaiBaseUrl,
          openaiModel: configData.openaiModel !== undefined ? configData.openaiModel : currentConfig.openaiModel
        };
        
        // 保存配置
        const success = saveConfig(combinedConfig);
        
        if (success) {
          this.message = '配置已成功保存';
          this.messageType = 'success';
          // 自动隐藏提示
          this.messageTimer = setTimeout(() => {
            this.message = '';
          }, 3000);
        } else {
          this.message = '保存配置失败';
          this.messageType = 'error';
        }
      } catch (error) {
        console.error('保存配置时出错:', error);
        this.message = '保存配置时发生错误';
        this.messageType = 'error';
      }
    },
    resetDefaults(type = 'all') {
      // 清除之前的定时器
      if (this.messageTimer) {
        clearTimeout(this.messageTimer);
        this.messageTimer = null;
      }
      
      // 恢复默认配置
      if (type === 'all' || type === 'ragflow') {
        this.config.apiKey = this.defaultConfig.apiKey;
        this.config.baseUrl = this.defaultConfig.baseUrl;
        this.config.chatId = this.defaultConfig.chatId;
      }
      
      if (type === 'all' || type === 'openai') {
        this.config.openaiApiKey = this.defaultConfig.openaiApiKey;
        this.config.openaiBaseUrl = this.defaultConfig.openaiBaseUrl;
        this.config.openaiModel = this.defaultConfig.openaiModel;
      }
      
      if (type === 'all') {
        // 清除localStorage中的配置
        localStorage.removeItem('ragflow_config');
      } else {
        // 只保存当前配置
        this.saveConfig();
      }
      
      // 显示消息
      this.message = type === 'all' ? '已恢复全部默认配置' : `已恢复${type === 'ragflow' ? 'RAGFlow' : 'OpenAI'}默认配置`;
      this.messageType = 'success';
      
      // 3秒后清除消息
      this.messageTimer = setTimeout(() => {
        this.message = '';
      }, 3000);
    }
  },
  beforeUnmount() {
    // 组件销毁前清理定时器
    if (this.messageTimer) {
      clearTimeout(this.messageTimer);
      this.messageTimer = null;
    }
  }
};
</script>

<style scoped>
.config-view {
  padding: 1rem;
}

.config-container {
  max-width: 800px;
  margin: 0 auto;
  background-color: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

h2 {
  color: var(--primary-color);
  margin-top: 0;
  margin-bottom: 1rem;
}

.description {
  color: var(--light-text-color);
  margin-bottom: 1rem;
}

.tabs {
  display: flex;
  margin-bottom: 2rem;
  border-bottom: 1px solid var(--border-color);
}

.tab {
  padding: 0.8rem 1.5rem;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  color: var(--light-text-color);
  font-weight: 500;
  transition: all 0.2s;
}

.tab:hover {
  color: var(--primary-color);
}

.tab.active {
  color: var(--primary-color);
  border-bottom-color: var(--primary-color);
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.form-control {
  width: 100%;
  padding: 0.8rem;
  font-size: 1rem;
  border: 1px solid var(--border-color);
  border-radius: 4px;
  background-color: #fafafa;
}

.form-control:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(7, 193, 96, 0.2);
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

button {
  padding: 0.8rem 1.5rem;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: none;
}

button.primary {
  background-color: var(--primary-color);
  color: white;
}

button.primary:hover {
  background-color: #06b057;
}

button.secondary {
  background-color: #F0F0F0;
  color: var(--text-color);
}

button.secondary:hover {
  background-color: #e5e5e5;
}

.message {
  margin-top: 1rem;
  padding: 0.8rem;
  border-radius: 4px;
}

.message.success {
  background-color: rgba(7, 193, 96, 0.1);
  color: #05944b;
}

.message.error {
  background-color: rgba(255, 75, 75, 0.1);
  color: #e03c3c;
}

.current-config {
  margin-top: 2rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.current-config h3 {
  font-size: 1rem;
  margin-top: 0;
  margin-bottom: 0.5rem;
}

pre {
  font-family: monospace;
  font-size: 0.9rem;
  color: #333;
  white-space: pre-wrap;
  word-break: break-all;
}

@media (max-width: 768px) {
  .config-container {
    padding: 1.5rem;
  }
  
  .tabs {
    flex-direction: column;
    border-bottom: none;
  }
  
  .tab {
    border-bottom: 1px solid var(--border-color);
    text-align: center;
  }
  
  .tab.active {
    border-bottom: 1px solid var(--primary-color);
    background-color: var(--primary-light);
  }
}
</style> 